<template>
  <content-box>
    <div class="box-title" slot="header" style="width: 100%;">
      <el-row style="width: 100%;">
        <el-col :xs="6" :sm="16" :md="20">
          <router-link :to="{ path: 'userAdd'}">
            <el-button type="primary" size="small" icon="el-icon-plus">{{$t('btns.add')}}</el-button>
          </router-link>
        </el-col>
        <el-col :xs="18" :sm="8" :md="4">
          <el-input size="small" placeholder="输入用户名称" v-model="searchKey" @keyup.enter.native="search($event)">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="search($event)"></i>
          </el-input>
        </el-col>
      </el-row>
    </div>

    <div slot="body">
      <el-table :data="tableData.rows" size="mini" border v-loading="listLoading" :height="tableFull(210)">
        <el-table-column
          prop="id"
          type="selection"
          width="40" align="center">
        </el-table-column>
        <el-table-column
          label="照片" width="76" align="center">
          <template slot-scope="scope">
            <img :src='scope.row.avatar' style="height: 35px;vertical-align: middle;" alt="">
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="名称">
        </el-table-column>
        <el-table-column
          prop="nickname"
          label="登录用户名">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          label="状态">
          <template slot-scope="scope">
            {{ scope.row.status===1 ? '已激活' : '未激活' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="335">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="default"
              @click="handleEdit(scope.$index, scope.row)">{{$t('btns.edit')}}
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleDeptConfig(scope.$index, scope.row)">{{$t('btns.config')}}{{$t('btns.department')}}
            </el-button>
            <el-button
              size="mini"
              type="primary"
              @click="handleRoleConfig(scope.$index, scope.row)">{{$t('btns.config')}}{{$t('btns.role')}}
            </el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)">{{$t('btns.delete')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination :class="{'border-pagination': true, 'pagination-right': true}"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="tableData.pagination.page"
        :page-sizes="pageList"
        :page-size="tableData.pagination.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableData.pagination.total">
      </el-pagination>

      <!-- 角色配置 -->
      <el-dialog class="dialog-select-tree" :title="$t('btns.config') + $t('btns.role') + dialogTitle" 
      :visible.sync="dialogVisible" width="30%">
        <div class="select-tree">
        <el-scrollbar
          tag="div"
          class='is-empty'
          wrap-class="el-select-dropdown__wrap"
          view-class="el-select-dropdown__list">
        <el-tree
          :data="roleData"
          ref="roleTree"
          show-checkbox
          check-strictly
          node-key="id"
          :default-checked-keys="selectRole"
          v-loading="dialogLoading"
          :props="defaultProps">
        </el-tree>
        </el-scrollbar>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitUserRoles">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 部门配置 -->
      <el-dialog class="dialog-select-tree" :title="$t('btns.config') + $t('btns.department') + dialogTitle" 
      :visible.sync="dialogDeptVisible" width="30%">
        <div class="select-tree">
        <el-scrollbar
          tag="div"
          class='is-empty'
          wrap-class="el-select-dropdown__wrap"
          view-class="el-select-dropdown__list">
        <el-tree
          :data="deptData"
          ref="deptsTree"
          show-checkbox
          check-strictly
          node-key="id"
          :default-checked-keys="selectDept"
          v-loading="dialogDeptLoading"
          :props="defaultDepts">
        </el-tree>
        </el-scrollbar>
        </div>
        <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogDeptVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitUserDepts">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 新增修改用户 -->
      <el-dialog class="form-add-edit dialog-dark-skin" :title="$t('btns.add') + $t('btns.department') + dialogTitle" 
      :visible.sync="dialogAddEditVisible" width="34%">
        <el-form :model="userForm" ref="userForm" label-width="100px" class="demo-userForm">
          <el-scrollbar tag="div" class='is-empty' style="padding-right: 1px;" wrap-class="el-select-dropdown__wrap" view-class="el-select-dropdown__list">
            <!-- 用户图片 -->
            <el-upload class="avatar-uploader" :show-file-list="false" 
              action="https://jsonplaceholder.typicode.com/posts/"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>

            <el-form-item class="avatar-left-input" label="用户名" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>
            <el-form-item class="avatar-left-input" label="姓名" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>
            
            <el-form-item class="avatar-left-input" label="性别">
              <el-radio size="small" class="radio" v-model="userForm.usable" border label="1">男</el-radio>
              <el-radio size="small" class="radio" v-model="userForm.usable" border label="0">女</el-radio>
              <el-radio size="small" class="radio" v-model="userForm.usable" border label="2">保密</el-radio>
            </el-form-item>

            <el-form-item label="密码" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>
            <el-form-item label="确认密码" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>
            
            <el-form-item label="所属部门">
              <el-select-tree size="small" :treeData="deptData" :propNames="defaultDepts" clearable
                              placeholder="请选择部门">
              </el-select-tree>
            </el-form-item>
            

            <el-form-item label="手机" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>

            <el-form-item label="邮箱" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>

            <el-form-item label="员工编号" prop="name">
              <el-input size="small" v-model="userForm.name"></el-input>
            </el-form-item>

            <el-form-item label="入职日期" prop="name">
              <el-date-picker size="small" v-model="userForm.name" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
              
            <el-form-item label="状态">
              <el-radio size="small" class="radio" v-model="userForm.usable" border label="1">已激活</el-radio>
              <el-radio size="small" class="radio" v-model="userForm.usable" border label="0">未激活</el-radio>
            </el-form-item>

          </el-scrollbar>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogAddEditVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="submitUserDepts">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </content-box>
</template>

<script>
  import { mapGetters } from 'vuex'
  import ContentBox from '@/views/layout/components/ContentBox'
  import { getUserList, userDel, userRoles, saveUserRoles, userDepts, saveUserDepts } from '@/api/user'
  import { getRoleList } from '@/api/role'
  import { getDepartmentList } from '@/api/department'
  import '@/styles/tree-menus.scss'

  export default {
    components: {
      ContentBox
    },
    computed: {
      ...mapGetters([
        'fullHeight',
        'pageList'
      ])
    },
    data() {
      return {
        searchKey: '',
        imageUrl: '',
        currentRow: {},
        dialogVisible: false,
        dialogDeptVisible: false,
        dialogDeptLoading: false,
        dialogAddEditVisible: false,
        listLoading: false,
        tableData: {
          rows: [],
          pagination: {
            total: 0,
            page: 1,
            limit: 10,
            parentId: 0
          }
        },
        roleData: [],
        deptData: [],
        selectDept: [],
        selectRole: [],
        dialogTitle: '',
        dialogLoading: false,
        defaultProps: {
          children: 'children',
          label: 'name',
          id: 'id'
        },
        defaultDepts: {
          children: 'children',
          label: 'name',
          id: 'id'
        },
        userForm: [],
        rules: {
          name: [
            { required: true, message: '请输入活动名称', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      handleAvatarSuccess() {
      },
      beforeAvatarUpload() {
      },
      tableFull(full) {
        return this.z_fullNum(this.fullHeight, full)
      },
      search(e) {
        this.load()
      },
      handleSizeChange(val) {
        this.tableData.pagination.limit = val
        this.load()
      },
      handleCurrentChange(val) {
        this.tableData.pagination.page = val
        this.load()
      },
      // 配置部门
      handleDeptConfig(index, row) {
        this.currentRow = row
        this.dialogTitle = ' - ' + row.nickname
        this.dialogDeptVisible = true
        this.dialogDeptLoading = true
        // 获取部门列表
        getDepartmentList().then(res => {
          this.deptData = []
          this.deptData.push(...res.data)
          this.dialogDeptLoading = false
        })
        // 获取所选角色
        userDepts({ id: row.id }).then(res => {
          this.selectDept = []
          this.selectDept = res.data
        })
      },
      // 配置角色
      handleRoleConfig(index, row) {
        this.currentRow = row
        this.dialogTitle = ' - ' + row.nickname
        this.dialogVisible = true
        // 获取角色列表
        getRoleList().then(res => {
          this.roleData = []
          this.roleData.push(...res.data)
          this.dialogLoading = false
        })
        // 获取所选角色
        userRoles({ id: row.id }).then(res => {
          this.selectRole = []
          this.selectRole = res.data
        })
      },
      // 保存用户部门
      submitUserDepts() {
        this.dialogDeptLoading = true
        const checkedKeys = this.$refs.deptsTree.getCheckedKeys()
        saveUserDepts({ id: this.currentRow.id, depts: checkedKeys }).then(res => {
          console.log('返回数据', res, checkedKeys)
          this.dialogDeptLoading = false
          this.dialogDeptVisible = false
        })
      },
      // 保存用户角色
      submitUserRoles() {
        this.dialogLoading = true
        const checkedKeys = this.$refs.roleTree.getCheckedKeys()
        saveUserRoles({ id: this.currentRow.id, roles: checkedKeys }).then(res => {
          console.log('返回数据', res, checkedKeys)
          this.dialogLoading = false
          this.dialogVisible = false
        })
      },
      // 修改
      handleEdit(index, row) {
        console.log(index, row, '修改')
        // this.$router.push({ name: 'UserAdd', query: { id: row.id }})
        this.dialogAddEditVisible = true
      },
      // 删除
      handleDelete(index, row) {
        userDel({
          id: row.id
        }).then(res => {
          // 刷新
          this.load()
        })
      },
      // 加载数据
      load() {
        this.listLoading = true
        getUserList({
          searchKey: this.searchKey,
          limit: this.tableData.pagination.limit,
          page: this.tableData.pagination.page
        }).then(res => {
          this.tableData.rows = res.data.rows
          this.tableData.pagination.total = res.data.total
          this.listLoading = false
          console.log(res)
        })
      }
    },
    created() {
      // 初始化数据
      this.load()
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
$avatarWidth: 150px;

  .form-add-edit{
    .el-form-item{
      margin-bottom: 15px;
      &.avatar-left-input{
        margin-right: $avatarWidth;
      }
    }
  }
</style>

<style rel="stylesheet/scss" lang="scss">
@import "src/styles/variables.scss";
$avatarWidth: 150px;
$avatarLeft: 12px;
$imgBoxWidth: $avatarWidth - $avatarLeft;

.form-add-edit{
  // 处理新增修改弹窗样式
  .el-dialog__header{
    background-color: $menuBg;
    .el-icon,
    .el-dialog__title{
      color: lighten($menuBg, 72%);
      font-weight: bold;
    }
  }

  .el-dialog__footer{
    border-top: 1px solid lighten($menuBg, 66%);
    background-color: lighten($menuBg, 70%);
    padding-bottom: 10px;
  }

  .el-select-dropdown__wrap{
    max-height: 60vh;
  }
  
  // 头像
  .avatar-uploader{
    display: inline-block;
    position: absolute;
    right: 0;
    .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 4px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: $imgBoxWidth;
      height: $imgBoxWidth;
      &:hover {
        border-color: #409EFF;
      }
      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: $imgBoxWidth;
        height: $imgBoxWidth;
        line-height: $imgBoxWidth;
        text-align: center;
      }
    }
  }
}



</style>